'use strict'

const nodeMajor = Number(process.versions.node.match(/^(\d+)\./)[1])
if (nodeMajor < 14) {
  console.error('[ERROR] Node.js v14 or above is required.\n')
  process.exit(1)
}

// Check if running in the correct directory
const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')
const packageJson = path.join(__dirname, '..', 'package.json')

if (!fs.existsSync(packageJson)) {
  console.error('[ERROR] Please run npm install from the project root directory.\n')
  process.exit(1)
}

// Force kill any running electron processes
try {
  execSync('taskkill /F /IM electron.exe /T', { stdio: 'ignore' })
} catch (err) {
  // Ignore if no process found
}

// Clean electron module with force
const electronPath = path.join(__dirname, '..', 'node_modules', 'electron')
if (fs.existsSync(electronPath)) {
  try {
    // Force remove read-only attributes
    execSync(`attrib -r "${electronPath}\\*.*" /s`, { stdio: 'ignore' })
    // Try native delete first
    fs.rmSync(electronPath, { recursive: true, force: true })
  } catch (err) {
    try {
      // If native delete fails, try with rd command
      execSync(`rd /s /q "${electronPath}"`, { stdio: 'inherit' })
    } catch (err2) {
      console.error('[ERROR] Failed to clean electron module. Please restart your computer and try again.\n')
      process.exit(1)
    }
  }
}

// Check write permissions with retry
let retries = 3
while (retries > 0) {
  try {
    const testPath = path.join(__dirname, '..', 'node_modules', '.test-dir')
    if (fs.existsSync(testPath)) {
      fs.rmSync(testPath, { recursive: true, force: true })
    }
    fs.mkdirSync(testPath, { recursive: true })
    fs.writeFileSync(path.join(testPath, '.write-test'), '')
    fs.rmSync(testPath, { recursive: true, force: true })
    break
  } catch (err) {
    retries--
    if (retries === 0) {
      console.error('[ERROR] Insufficient permissions. Please run as administrator.\n')
      process.exit(1)
    }
    // Wait for 2 seconds before retry
    execSync('timeout /t 2', { stdio: 'ignore' })
  }
}

// All checks passed
process.exit(0)
